package com.tl.khadmin.service.impl;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.tl.khadmin.HaolibeiApi;
import com.tl.khadmin.bean.*;
import com.tl.khadmin.bean.dto.ProductSupplyDetailDto;
import com.tl.khadmin.mapper.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.tl.khadmin.bean.Order;
import com.tl.khadmin.bean.OrderException;
import com.tl.khadmin.bean.Staff;
import com.tl.khadmin.bean.Supplier;
import com.tl.khadmin.enums.OrderStateEnum;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.OrderIService;
import com.tl.khadmin.util.CommonUtil;
import com.tl.khadmin.util.Constant;
import com.tl.khadmin.util.PutParamUtil;
import sun.rmi.runtime.Log;

@Service
public class OrderServiceImpl implements OrderIService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderProductMapper orderProductMapper;
    @Resource
    private OrderExceptionMapper orderExceptionMapper;
    @Resource
    private CityMapper cityMapper;
    @Resource
    private ProductSupplyMapper productSupplyMapper;
    @Resource
    private ProductSupplySpecificationMapper productSupplySpecificationMapper;
    @Resource
    private LogisticsMapper logisticsMapper;

	@Override
	public Page<Order> showOrderByPage(HttpSession session, Integer pageNum, Integer pageSize, Map<String, Object> params) {
		Page<Order> page=new Page<Order>(pageNum, pageSize);
        params.put("page", page);  
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        PutParamUtil.setParamIsInterior(supplier, params);	//设置查询供应商数据范围 
        String statusArr = params.get("statusArr").toString();
        String[] statusList = null;
        if (StringUtils.isNotBlank(statusArr)) {
            statusList = statusArr.split(",");
        }
        params.put("statusList", statusList);
        List<Order> list = orderMapper.selectOrderByPage(params);
        page.setResult(list);
        return page;
    }

    @Override
    public Map<String, Object> showOrderInfo(Integer id) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("order", orderMapper.selectByPrimaryKey(id));
        result.put("orderProductList", orderProductMapper.queryByOrderId(id));
        return result;
    }

    @Override
    public String acceptOrder(String orderIds) {
        String[] idsArr = orderIds.substring(0, orderIds.length() - 1).split(",");
        try {
            for (String id : idsArr) {
            	//仅限已付款订单能受理
            	if(orderMapper.selectByPrimaryKey(Integer.parseInt(id)).getStatus().code() == OrderStateEnum.已付款.code()){
            		orderMapper.updateStatus(id, OrderStateEnum.报关中.code());
            	} 
            }
        } catch (Exception ex) {
            return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
        }
        return CommonUtil.returnMapResultByRows(1, "提交成功", "提交失败，请重试");
    }

    @Override
    public Map<String, String> uploadAbnormalImg(String basePath, MultipartFile file) {
        Map<String, String> ret = new HashMap<String, String>();
        if (file == null) {
            ret.put("result", "fail");
            return ret;
        }
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddhhmmssSSS");
            File imgDir = new File(basePath);
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            String datePath = df.format(new Date());
            String picurl = datePath + ".jpg";
            File toFile = new File(basePath, picurl);
            file.transferTo(toFile);
            ret.put("result", "success");
            ret.put("message", "/upload/productimg/" + picurl);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            ret.put("reulst", "fail");
            return ret;
        }
    }

    /**
     * 保存订单异常信息
     */
    @Override
    public String saveOrderException(HttpSession session, OrderException orderException) {
        try {
            Staff staff = (Staff) session.getAttribute(Constant.USER);
            //设置订单为异常
            Order ord = new Order();
            ord.setId(orderException.getOrderId());
            ord.setAbnormalStatus(2); 
            if(orderMapper.updateByPrimaryKeySelective(ord) == 1){
            	orderException.setCreateTime(new Date());
                orderException.setCreateId(staff.getId());
                int row = orderExceptionMapper.insertSelective(orderException);
                return CommonUtil.returnMapResultByRows(row, "提交成功", "提交失败，请重试");
            } 
        } catch (Exception ex) {
            return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
        }
        return CommonUtil.returnMapResultToJson("fail", "提交失败");
    }

    @Override
    public String saveOrderLogistics(HttpSession session, Order order) {
        try {
            Staff staff = (Staff) session.getAttribute(Constant.USER);
            Order ord = new Order();
            ord.setId(order.getId());
            ord.setLogisticsId(order.getLogisticsId());
            ord.setLogisticsNumber(order.getLogisticsNumber());
            ord.setStatus(OrderStateEnum.已发货);
            ord.setDeliveryTime(new Date());
            int row = orderMapper.updateByPrimaryKeySelective(ord);
            sendOrderDeliver(order);
            if (row != 1) {
                return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
            }

        } catch (Exception ex) {
            return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
        }
        return CommonUtil.returnMapResultByRows(1, "提交成功", "提交失败，请重试");
    }

    private void sendOrderDeliver(Order ord){
        try{
            Order order = orderMapper.selectByPrimaryKey(ord.getId());
            Logistics logistics =  logisticsMapper.selectByPrimaryKey(ord.getLogisticsId());
            Map<String, String> params = new HashMap<>();
            params.put("tradeid",order.getOrderId());
            params.put("freightCode", logistics.getLogisticsCode());
            params.put("freightName", logistics.getLogisticsName());
            params.put("freightNo", ord.getLogisticsNumber());
            String result =  HaolibeiApi.orderDeliverbillpost(params);
        }
        catch (Exception ex){
            String a  = ex.getMessage();
        }
    }

    @Override
    public String saveOrder(OpenOrder openOrder) {
        try {
            int orderIdOld = orderMapper.selectOrderIdByOrderNumber(openOrder.getTradeId());
            if(orderIdOld>0){
                return "1001";
            }
            Order order = new Order();
            order.setLogisticsId(6);
            order.setOrderId(openOrder.getTradeId());
            order.setCreateTime(new Date());
            order.setTradeType((short) 1);
            order.setReceiver(openOrder.getEShopBuyer().getCustomerReceiver());
            order.setReceiverAddress(openOrder.getEShopBuyer().getCustomerAllAddress());
            order.setReceiverProid(cityMapper.getProidBuyName(openOrder.getEShopBuyer().getCustomerReceiverProvince()));
            order.setReceiverCityid(cityMapper.getCityIdBuyName(openOrder.getEShopBuyer().getCustomerReceiverCity()));
            order.setReceiverDistrictid(cityMapper.getDistrictBuyName(openOrder.getEShopBuyer().getCustomerReceiverDistrict()));
            order.setReceiverPcdt(openOrder.getEShopBuyer().getCustomerReceiverProvince() + openOrder.getEShopBuyer().getCustomerReceiverCity()
            		+ openOrder.getEShopBuyer().getCustomerReceiverDistrict());
            order.setReceiverIdnumber(openOrder.getEShopBuyer().getIdCard());
            order.setReceiverMobile(openOrder.getEShopBuyer().getCustomerReceiverMobile());
            order.setStatus(OrderStateEnum.未报关);
            order.setFreight(openOrder.getCustomerFreightFee());
            order.setOrderAmount(openOrder.getTotal());
            order.setProductTotalAmount(openOrder.getTotal());
            order.setAbnormalStatus(1);
            order.setOrderRemark(openOrder.getBuyerMessage());
            order.setMerchantRemark(openOrder.getSellerMemo());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(openOrder.getTradePaiedTime());
            order.setPaymentTime(date);
            orderMapper.insertSelective(order);
            int orderId = orderMapper.selectOrderIdByOrderNumber(openOrder.getTradeId());
            Long supplyId = Long.valueOf(0);
            for (OpenOrderDetail detail : openOrder.getOrderDetails()
            ) {
                int productSupplyId = productSupplyMapper.getOrderDefaultSupply(detail.getBarcode(), detail.getExpdate());
                if(productSupplyId>0) {
                    ProductSupplyDetailDto supplyDetailDto = productSupplyMapper.queryProductSupplyDetailById((long) productSupplyId);

                    if (supplyId == 0) {
                        supplyId = supplyDetailDto.getSupplierId();
                    }
                    OrderProduct orderProduct = new OrderProduct() {{
                        setOrderId(orderId);
                        setProductSupplyId(productSupplyId);
                        setDateType(1);
                        setCode(detail.getPtypeid());
                        setDateValue(detail.getExpdate());
                        setNum(detail.getQty().intValue());
                        setProductName(detail.getProductname());
                        setSpecificationNumber(detail.getQty().intValue());
                        setPrice(detail.getPrice());
                        setCode(detail.getBarcode());
                    }};
                    try {
                        //设置订单中商品的供货价
                        List<ProductSupplySpecification> specList =
                                productSupplySpecificationMapper.getBySupplyIdAndNumber(productSupplyId, orderProduct.getSpecificationNumber());
                        if (specList != null && specList.size() > 0) {
                            ProductSupplySpecification specification = specList.stream().filter(p -> p.getNumber().compareTo(orderProduct.getSpecificationNumber()) == 0).findFirst().orElse(null);
                            if (specification != null) {
                                orderProduct.setUnitPrice(specification.getUnitPrice().floatValue());
                            } else {
                                orderProduct.setUnitPrice(specList.get(0).getUnitPrice().floatValue());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    orderProductMapper.insert(orderProduct);
                }
                else {
                    orderMapper.deleteByPrimaryKey(orderId);
                    return "1002";
                }

            }
           orderMapper.updateOrderSupplierId(supplyId.intValue(),orderId);
            return  "1000";
        }
        catch (Exception ex){
            return  String.format("订单新增失败：%s,异常：%s",openOrder.getTradeId(),ex.getMessage());
        }
    }


}
